package com.zhenyi.xiaohuoche.index;

import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.wxpay.utils.MD5Util;
import com.xhc.common.model.XhcOrder;
import com.xhc.common.model.XhcPresent;
import com.xhc.common.model.XhcTicket;
import com.xhc.common.model.XhcUserPresent;
import com.xhc.common.model.XhcUserTicket;
import com.zhenyi.xhc.core.OrderUtils;
import com.zhenyi.xhc.core.TicketUtils;
import com.zhenyi.xhc.core.XHCController;
import com.zhenyi.xhc.core.aes.Encrypt;

import cn.hutool.core.codec.Base64;

public class BillController extends XHCController {

	public void test() {
		String en = "nbu6z6ArDuINtopIL5NstrzoMpp+tAhqglT6IhH0u+JaczD6gFXaKB+3sm9YvJYRDPhm8OTLAVwrlOKr0Jf2S36DyhUgxFB+B9VpxWZVUqFZVRPcIKPlzXPb8+J93Q4Xqz/IBXMxQ/3L0KqbzT3DPqMHVqDeXDI1QELH0zUmuXYk5pC8HLp2Gz1P6OCQTSS5IBhNoprdSOJgvivDVnurNjLAGdiST0iosOMRLUNU9qNjIdmEg6IGZvnl5tQxaslhTUJmhfxKXPhtQZEtQ9tvhtnuJisNEbaMNmi+H7YtUoz3mED9vbVJhxv/L/x6XnP/N42KB4eW+Kbbd+8hbZh/KU3NJaMBTp2fSXbLNvsrSWQanmnYL6VLqDJ+DAefQmusih3CnDKs+9K9YkyhAksnvOwDyLiKKYNIoRkufwubiWpMdDQZQqvnOTF6iMHMb6P0qohzzq7dGgh/eCfOCRyamPC17TvO7xk3FAptiYDwjYkdJigXDCUv4+Kal+ZHjfbjk6ElWptUiHBIVxb4YuAl953Ce0ethziZ9y2ptMzgFzVcrr4GI8WdaSQVAs2uEVg6f2jHFB78F4lXzJiP1HTyBbsoi/CX4g0+7KMAcUZRoYLGc2TKBZWrJ9H4dzIt5/w9Mr0wxVZjQ4RVdIqUvb1/qumbApZzUsguPcbdRKyuuQxfh+TT2gJlU4qfA/FMQQGC0lIl6YjR3IS1cxQOtDJA9Kmy2fPCTtDm/4RirV3nZtWfx8V3/LGE4WxY2c3XLHvYSgdtR7emJ7V4UP1ZUaJWalANCudEUbEL8lcku9gsRdeYyqUcm0US5FJ4spUhGijudIoArrucuCaCBQiz2skhW92QDqcyRq3Lk+kg50PAlQ9JOnFdWHru2QIRNHE3SxE5HeD7kZhzy25soFj6HBOdb7JuglF5e/NQ9LRI8EYOS45Kb5QjFEwfQwKjCj3JxUup7tBXoy6ICyUw12tIgtT6EfLFekOrl6g7TDeOLZh/NFcpkR0ohV0GagQG5l3eWA2OJYXCiEdMERTVa0yUPm6cRpSZj2nJOlLWk+8A942Y5jU=";
		// String b64 = Base64Utils.decode(en);
		// System.out.println(b64);
		// System.out.println(PARTNER_KEY);
		// System.out.println(PARTNER_KEY.length());
		// String key = MD5Util.MD5Encode(PARTNER_KEY, "utf-8");
		// System.out.println(key);
		// System.out.println(key.length());
		// String de = Encrypt.Aes256Decode(Base64.decode(en), key.getBytes());
		// System.out.println(de);
		Map<String, String> result = getDeResult(en);
		String refund_status = result.get("refund_status");
		if (!"SUCCESS".equals(refund_status)) {
			renderPaySuccess();
			return;
		}
		String out_trade_no = result.get("out_trade_no");
		Long id = hashids.decode(out_trade_no)[0];
		XhcOrder order = XhcOrder.dao.findById(id);
		order.updateOrderStatus();
		renderSuccess();
	}

	private Map<String, String> getDeResult(String en) {
		String key = MD5Util.MD5Encode(PARTNER_KEY, "utf-8");
		String de = Encrypt.Aes256Decode(Base64.decode(en), key.getBytes());
		Map<String, String> result = PaymentKit.xmlToMap(de);
		return result;
	}

	@Clear
	@Before(Tx.class)
	public void billRefund() {
		String xmlResult = HttpKit.readData(getRequest());
		if (StrKit.isBlank(xmlResult)) {
			renderFailure("no xmlResult");
			renderPayFail();
			return;
		}
		// if (DEBUG) {
		// LogKit.info(xmlResult);
		// }
		Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
		// String result_code = result.get("result_code");
		String return_code = result.get("return_code");
		if (!"SUCCESS".equals(return_code)) {
			LogKit.warn("返回失败");
			renderPayFail();
			return;
		}

		String req_info = result.get("req_info");
		Map<String, String> refundResult = getDeResult(req_info);
		String refund_status = refundResult.get("refund_status");
		if (!"SUCCESS".equals(refund_status)) {
			renderPaySuccess();
			return;
		}
		String out_trade_no = refundResult.get("out_trade_no");
		Long id = hashids.decode(out_trade_no)[0];
		XhcOrder order = XhcOrder.dao.findById(id);
		order.updateOrderStatus();
		if ("ticket".equals(order.getAttach())) {
			XhcUserTicket userTicket = XhcUserTicket.dao.searchFirst("orderId", order.getId());
			XhcTicket.dao.increase(userTicket.getTicketId());
		} else if ("present".equals(order.getAttach())) {
			XhcUserPresent userPresent = XhcUserPresent.dao.searchFirst("orderId", order.getId());
			userPresent.setStatus(-1);
			userPresent.update();
			XhcPresent.dao.increase(userPresent.getPresentId());
		}
		renderPaySuccess();
	}

	@Clear
	@Before(Tx.class)
	public void billPush() {
		// try {
		String xmlResult = HttpKit.readData(getRequest());
		if (StrKit.isBlank(xmlResult)) {
			renderFailure("no xmlResult");
			renderPayFail();
			return;
		}
		// if (DEBUG) {
		// LogKit.info(xmlResult);
		// }
		Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
		// String appid = result.get("appid");
		String bank_type = result.get("bank_type");
		String cash_fee = result.get("cash_fee");
		String fee_type = result.get("fee_type");
		String is_subscribe = result.get("is_subscribe");
		// String mch_id = result.get("mch_id");
		// String nonce_str = result.get("nonce_str");
		// String openid = result.get("openid");
		String out_trade_no = result.get("out_trade_no");
		String result_code = result.get("result_code");
		String return_code = result.get("return_code");
		String sign = result.get("sign");
		String time_end = result.get("time_end");
		String total_fee = result.get("total_fee");
		String trade_type = result.get("trade_type");
		String transaction_id = result.get("transaction_id");
		String attach = result.get("attach");
		if (!"SUCCESS".equals(return_code)) {
			LogKit.warn("返回失败 " + out_trade_no);
			LogKit.warn(xmlResult);
			renderPaySuccess();
			return;
		}
		if (!"SUCCESS".equals(result_code)) {
			LogKit.warn("支付结果失败 " + out_trade_no);
			LogKit.warn(xmlResult);
			renderPaySuccess();
			return;
		}
		// System.out.println(JsonKit.toJson(result));
		// System.out.println("--------");
		// System.out.println(JsonKit.toJson(result));
		// System.out.println("out_trade_no: " + out_trade_no);
		// System.out.println("total_fee: " + total_fee);
		// System.out.println("cash_fee: " + cash_fee);
		// System.out.println("out_trade_no: " + out_trade_no);
		// System.out.println("--------");

		long id = hashids.decode(out_trade_no)[0];
		XhcOrder order = XhcOrder.dao.findById(id);
		String partnerKey = PARTNER_KEY;
		String mySign = PaymentKit.createSign(result, partnerKey);
		if (!mySign.equals(sign)) {
			// order.setVerify(1);
			renderPayFail();
			return;
		} else {
			// order.setVerify(0);
		}

		order.setBankType(bank_type);
		order.setIsSubscribe(is_subscribe);
		order.setTradeType(trade_type);
		order.setTransactionId(transaction_id);
		order.setFeeType(fee_type);
		order.setTimeEnd(time_end);
		order.setCashFee(cash_fee);
		order.setPaid(Integer.parseInt(total_fee));
		order.update();

		order.updateOrderStatus();

		if (StrKit.notBlank(attach)) {
			if ("ticket".equals(attach)) {
				SqlPara sqlPara = xhcDb.getSqlPara("OrderTickets", order.getId());
				List<XhcUserTicket> items = XhcUserTicket.dao.find(sqlPara);
				for (XhcUserTicket xhcUserTicket : items) {
					xhcUserTicket.setStatus(1);
					String no = OrderUtils.gen(xhcUserTicket.getId());
					xhcUserTicket.setNo(no);
					Long userTicketId = xhcUserTicket.getId();
					String code = piaoHashids.encode(userTicketId);
					String qrcodeUrl = TicketUtils.qrcodeImage(code, no, xhcUserTicket.getTitle(),
							"时间: " + xhcUserTicket.getTime());
					xhcUserTicket.setQrcode(qrcodeUrl);
					xhcUserTicket.update();
					try {
						XhcTicket.dao.increase(xhcUserTicket.getTicketId());
					} catch (Exception e) {
						LogKit.warn("increase ticket error");
					}
				}
				if (items.size() > 0) {
					try {
						Long ticketId = items.get(0).getTicketId();
						LogKit.info("pay ticket id " + ticketId);
						XhcTicket ticket = XhcTicket.dao.findById(ticketId);
						ticket.updateTicketCount();
					} catch (Exception e) {
						LogKit.error("update ticket error ", e);
					}
				}
			} else if ("present".equals(attach)) {
				XhcUserPresent userPresent = XhcUserPresent.dao.searchFirst("orderId", id);
				userPresent.setStatus(1);
				userPresent.setNo(OrderUtils.gen(userPresent.getId()));
				userPresent.update();
				if (userPresent != null) {
					XhcPresent present = XhcPresent.dao.findById(userPresent.getPresentId());
					present.setCount(present.getCount() - userPresent.getCount());
					present.update();
				}
			}
		}

		// CdCard card = CdCard.dao.findById(order.getCardId());
		// Integer left = card.getLeft();
		// if (left != null) {
		// left -= 1;
		// if (left <= 0) {
		// left = 0;
		// }
		// card.setLeft(left);
		// card.update();
		// }
		// order.updateOrderStatus();

		if (order.getStatus().equals(1)) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					// confirmBillOrder(order);
				}
			}).start();
		}
		// }
		renderPaySuccess();
		// } catch (Exception e) {
		// e.printStackTrace();
		// renderFailure();
		// }
		// renderSuccess();

	}

	private void renderPayFail() {
		String returnXML = "<xml>\n" + "<return_code><![CDATA[FAIL]]></return_code>\n"
				+ "<return_msg><![CDATA[FAIL]]></return_msg>\n" + "</xml>";
		renderText(returnXML, "text/xml");
	}

	private void renderPaySuccess() {
		String returnXML = "<xml>\n" + "<return_code><![CDATA[SUCCESS]]></return_code>\n"
				+ "<return_msg><![CDATA[OK]]></return_msg>\n" + "</xml>";
		renderText(returnXML, "text/xml");
	}

}
